package models

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/garyburd/redigo/redis"
	"time"
)

var(
	pool *redis.Pool
	redisHost = beego.AppConfig.String("reidsHost")
	reidsPort = beego.AppConfig.String("reidsPort")
)

//newRedisPool:创建redis连接池
func newRedisPool()*redis.Pool{
	return &redis.Pool{
		MaxIdle:50,
		MaxActive:30,
		IdleTimeout:300*time.Second,
		Dial: func() (redis.Conn,  error) {
			c,err := redis.Dial("tcp",redisHost+":"+reidsPort)
			if err != nil {
				fmt.Println(err)
				return nil,err
			}
			//2、访问认证
			//if _, err =c.Do("AUTH",redisPass);err!=nil{
			//	c.Close()
			//	return nil,err
			//}
			return c,nil
		},
		//定时检查redis是否出状况
		TestOnBorrow: func(conn redis.Conn, t time.Time) error {
			if time.Since(t)<time.Minute{
				return nil
			}
			_,err := conn.Do("PING")
			return err
		},
	}
}

//初始化redis连接池
func init(){
	pool = newRedisPool()
}

//对外暴露连接池
func RedisPool()*redis.Pool{
	return pool
}